var auths = {};
mui.init({
	keyEventBind: {
		backbutton: false //关闭back按键监听
	}
});
mui.plusReady(function() {
	// 获取登录认证通道
	
	plus.oauth.getServices(function(services){
		var txt="登录认证通道信息：";
		for(var i in services){
			var service=services[i];
			console.log(service.id+": "+JSON.stringify(service.authResult)+", "+JSON.stringify(service.userInfo));
			auths[service.id]=service;
			var de=document.createElement('div');
			de.setAttribute('class','button');
			de.setAttribute('onclick','login(this.id)');
			de.id=service.id;
//			de.innerText=service.description+"登录";
			if(oauth){
				oauth.appendChild(de);
			}
		}
//		info.innerText=txt;
	},function(e){
//		outLine("获取登录认证失败："+e.message);
	});
	//关闭启动页
	setTimeout(function() {
		plus.navigator.closeSplashscreen();
	}, 200);
	// var main = plus.webview.getWebviewById('index_menu.html');
	// if(main){
	// 	plus.webview.close(main);
	// }

	var user_name = '',
		user_pwd = '',
		user_name_flag = false;
	//	注册点击跳转
	$('.btn-reg').on('tap', function(e) {
		e.preventDefault();
		$('#username').off('blur');
		mui.openWindow('/pages/login/registe.html');
	});
	//忘记密码点击跳转
	$('.forget-pwd').on('tap', function(e) {
		e.preventDefault();
		mui.openWindow('/pages/login/forget_pwd.html');
		return false;
	});
	//密码可见图标点击事件
	$('.pwd-wrap i').on('tap', function(e) {
		e.preventDefault();
		$('#password').off('focus');
		var type = $('#password').attr('type'),
			i = $(this);
		if(type == 'password') {
			$('#password').attr('type', 'text');
			i.css({
				'background-position-y': '-11px'
			});
		} else {
			$('#password').attr('type', 'password');
			i.css({
				'background-position-y': '6px'
			});
		}
	});
	//	登录按钮点击事件
	$('.btn-login').on('tap', function(e) {
		e.preventDefault();
		user_name = $('#username').val();
		user_pwd = $('#password').val();
		if(user_name && user_pwd) {
			myAjax('login/front_user/checkUserIsExist', 'post', {
				'username': user_name
			}, function(data) {
				if(!data.success) {
					mui.alert('该用户名不存在,请重新输入', '提示');
					$('#username').focus();
				} else {
					myAjax('login/front_user/login', 'post', {
						'username': user_name,
						'password': user_pwd
					}, function(data) {
						if(data.success) {
							if(data.data.headimgurl.indexOf('http://') == -1 && data.data.headimgurl.indexOf('https://') == -1){
								var headImg = _baseUrl+data.data.headimgurl;
							}else{
								var headImg = data.data.headimgurl;
							}
							plus.storage.setItem('cg_headimgurl',headImg);
							plus.storage.setItem('cg_user_id', data.data.uid + '');
							plus.storage.setItem('cg_user_token', data.data.user_token + '');
							plus.storage.setItem('cg_nickname', data.data.nickname + '');
							plus.storage.setItem('cg_uuid', plus.device.uuid);
							//保存版本号
							plus.runtime.getProperty(plus.runtime.appid,function(inf){
								wgtVer=inf.version;
								plus.storage.setItem('old_wgtVer',wgtVer);
//								console.log(wgtVer);
//								console.log('页面时登陆页');
							})
							
							var info = plus.push.getClientInfo(),
								token = info.token,
								clientid = info.clientid,
								userid = data.data.uid;
							myAjax('login/front_user/sendClientId','get',{
								'client_id':clientid,
								'token':token,
								'userid':userid
							},function(data){
								console.log(JSON.stringify(data))
								
							});
							mui.openWindow({
								url: '/pages/index/index_menu.html',
								id: 'index_menu.html'
							});
							
						} else {
							mui.alert('密码有误，请重新输入', '提示');
						}
					});
				}
			});
		} else if(!user_name) {
			mui.alert('请输入手机号', '提示');
		} else {
			mui.alert('请输入密码', '提示');
		}
	});

	//输入框上弹效果
	$('.focus').focus(function(){
		console.log('获取焦点');
		$('.login').animate({scrollTop:200}, 'slow');
	})
});


// 登录认证
function login(id){
//	outSet("----- 登录认证 -----");
	var auth=auths[id];
	if(auth){
		var w=null;
		if(plus.os.name=="Android"){
			w=plus.nativeUI.showWaiting();
		}
		document.addEventListener("pause",function(){
			setTimeout(function(){
				w&&w.close();w=null;
			},2000);
		}, false );
		auth.login(function(){
			w&&w.close();w=null;
//			outLine("登录认证成功：");
//			outLine(JSON.stringify(auth.authResult));
			userinfo(auth);
		},function(e){
			w&&w.close();w=null;
//			outLine("登录认证失败：");
//			outLine("["+e.code+"]："+e.message);
			plus.nativeUI.alert("登陆失败，请重新登录！",null,"登录失败");
		});
	}else{
//		outLine("无效的登录认证通道！");
		plus.nativeUI.alert("无效的登录认证通道！",null,"登录失败");
	}
}
// 获取用户信息
function userinfo(a){
	a.getUserInfo(function(){
		myAjax('login/front_user/weixinLogin','post',{
			'openid':a.userInfo.openid,
			'unionid':a.userInfo.unionid,
			'nickname':a.userInfo.nickname,
			'headimgurl':a.userInfo.headimgurl,
			'sex':a.userInfo.sex,
			'province':a.userInfo.province,
			'city':a.userInfo.city,
			'language':a.userInfo.language
		},function(data){
			console.log(JSON.stringify(data));
			if(data.success) {
				plus.storage.setItem('cg_user_id', data.data.uid + '');
				plus.storage.setItem('cg_user_token', data.data.user_token + '');
				plus.storage.setItem('cg_nickname', data.data.nickname + '');
				plus.storage.setItem('cg_uuid', plus.device.uuid);
				//保存版本号
				plus.runtime.getProperty(plus.runtime.appid,function(inf){
					wgtVer=inf.version;
					plus.storage.setItem('old_wgtVer',wgtVer);
				})
				
				var info = plus.push.getClientInfo(),
					token = info.token,
					clientid = info.clientid,
					userid = data.data.uid;
				myAjax('login/front_user/sendClientId','get',{
					'client_id':clientid,
					'token':token,
					'userid':userid
				},function(data){
					console.log(JSON.stringify(data))
					
				});
				mui.openWindow({
					url: '/pages/index/index_menu.html',
					id: 'index_menu.html'
				});
				var nickname=a.userInfo.nickname||a.userInfo.name||a.userInfo.miliaoNick;
				plus.nativeUI.alert(nickname+",欢迎登录！");
			}else{
				mui.toast('登陆失败！');
			}
		})
	},function(e){
//		outLine("获取用户信息失败：");
//		outLine("["+e.code+"]："+e.message);
		plus.nativeUI.alert("获取用户信息失败！",null,"登录失败");
	});
}
// 注销登录
function logoutAll(){
//	outSet("----- 注销登录认证 -----");
	for(var i in auths){
		logout(auths[i]);
	}
}
function logout(auth){
	auth.logout(function(){
//		outLine("注销\""+auth.description+"\"成功");
	},function(e){
//		outLine("注销\""+auth.description+"\"失败："+e.message);
	});
}